#!/bin/bash

# ---------- 配置 JAVA_HOME ----------
JAVA_PATH=$(readlink -f $(which java))
JAVA_HOME=$(echo "$JAVA_PATH" | sed 's:/bin/java::')
export PATH=$JAVA_HOME/bin:$PATH

echo "JAVA_HOME set to: $JAVA_HOME"

# ---------- 拷贝配置文件 ----------
if [ -f "$JAVA_HOME/CDFDevice.conf" ]; then
    echo "CDFDevice.conf already exists in $JAVA_HOME/, skipping copy."
else
    if [ -f "CDFDevice.conf" ]; then
        cp CDFDevice.conf "$JAVA_HOME/"
        echo "Copied CDFDevice.conf to $JAVA_HOME/"
    else
        echo "Warning: CDFDevice.conf not found in current directory!"
    fi
fi

# ---------- 编译项目 ----------
echo "Compiling Java sources..."
echo "编译命令为："
echo "$JAVA_HOME/bin/javac -d out -cp \"CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" JCECrypto.java CDFSM2.java ComFun.java"
$JAVA_HOME/bin/javac -d out -cp "CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar" \
    JCECrypto.java CDFSM2.java ComFun.java
echo

if [ $? -ne 0 ]; then
    echo "Compilation failed!"
    exit 1
else
    echo "Compilation succeeded."
fi

# ---------- 运行示例命令 ----------
echo
echo "下面是几个示例运行命令，请根据需要复制执行："
echo

echo "1. 加密数据示例："
echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto encrypt -cert \"MIIBoTCCAUWgAwIBAgIIRcqC+k8GG5YwDAYIKoEcz1UBg3UFADAhMQswCQYDVQQGEwJDTjESMBAGA1UEAwwJ5qC56K+B5LmmMCAXDTIzMTAxMDE2MDAwMFoYDzIwNTMxMDAyMT6wMDA0WjAhMQswCQYDVQQGEwJDTjESMBAGA1UEAwwJ5qC56K+B5LmmMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEuU1w2nF9qRirc78jRFZLZ/RVQLUMXUi9IdofqQTgAVQFXayqewvCYZkBKXdOWyXjl6goUwBcp7AHBdQIFtfQU6NjMGEwHwYDVR0jBBgwFoAUmNcVyA4Q/Vfrrm1CUSBOumpHPk4wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAc4wHQYDVR0OBBYEFJjXFcgOEP1X665tQlEgTrpqRz5OMAwGCCqBHM9VAYN1BQADSAAwRQIgdquZAwZCXLtUZPLFds9d2mDRYhYqVt0JVEaNYwxNcM8CIQDudMwc2f5JU9GI/BMyq0El5ww2Bx6GQM2Iq2AxBsptcQ==\" -data \"AAECAwQFBgcICQoLDA0ODw==\""
echo

echo "2. 生成 SM4 密钥："
echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto genkey -type SM4"
echo

echo "3. 生成 SM1 密钥："
echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto genkey -type SM1"
echo

echo "4. 生成 SM4 分散密钥："
echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto genkey -type DERIVED_SM4 -diver \"YWFhYWFhYWE=\" -rootkey \"wxH/pk50/OZmx0xuhHZoXA==\""
echo
